<?php

namespace Mall\Controller;

use Think\Controller;

class MallController extends Controller {

    //list
    public function index() {
        $config = M('Mall_config');
        $condata = $config->where('id=1')->find();
        $this->assign('config', $condata);
        $mod = M('Mall_product');
        $where['status'] = array('neq', 3);
        $list = $mod->where($where)->select();
        $this->assign('list', $list);
        $this->display();
    }

    //商品详细
    function desc() {
        $id = intval($_REQUEST['id']);
        $this->getProductById($id);
        $this->display('desc');
    }

    //兑换
    public function exchange() {
        $id = intval($_REQUEST['id']);
        $this->getProductById($id);
        $this->assign('id', $id);
        $this->display();
    }

    //兑换逻辑处理
    function doExchange() {
        $ajax['status'] = 0;
        $id = intval($_REQUEST['id']);
        $mod = M('Mall_order');
        $gc = M('Mall_product');
        $scorelog = M('Score_scorelog');
        $info = $gc->where('id=' . $id)->find();
        $huiyuaninfo = check_vip(wx_openid());
        if (322 >= $info['score']) {
            if ($info['sale_total'] < $info['total']) {
                $arr = array(
                    'pid' => $id,
                    'score' => $info['score'],
                    'price' => $info['price'],
                    'card_no' => 555555,
                    'openid' => 555555,
                    'status' => 2,
                    'ctime' => date('Y-m-d H:i:s')
                );
                $state = $mod->add($arr);
                if ($state) {
                    $sale_total = $info['sale_total'] + 1;
                    $gc->where('id='.$id)->setField('sale_total',$sale_total);
                    $scorelog->add(array('huiyuanid'=>1,'score'=>1,'huiyuantel'=>1,'huiyuanopenid'=>1,'ctime'=>date('Y-m-d H:i:s'),'type'=>1));
                    $ajax['status'] = 1;
                    $ajax['oid'] = $state;
                    $this->ajaxReturn($ajax);
                    
                } else {
                    $ajax['info'] = "兑换失败,请重试";
                    $this->ajaxReturn($ajax);
                }
            } else {
                $ajax['info'] = "库存不在";
                $this->ajaxReturn($ajax);
            }
        } else {
            $ajax['info'] = "积分不足";
            $this->ajaxReturn($ajax);
        }
    }

    //显示兑奖成功的兑奖码
    function showcode() {
        $this->display('success');
    }

    //根据ID查询商品基本信息
    private function getProductById($id) {
        $mod = M('Mall_product');
        $data = $mod->where('id=' . $id)->find();
        $this->assign('data', $data);
    }

}
